package com.erp.gather.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.gather.mapper.ErpSellerStorePromotionActivityMapper;
import com.erp.gather.service.IErpPythonMethodCallService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.redis.config.RedisConfig;
import com.ruoyi.common.redis.utils.RedisUtils;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStorePromotionActivity;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;

@RequiredArgsConstructor
@Service
public class ErpPythonMethodCallServiceImpl implements IErpPythonMethodCallService {
    @Resource
    RemoteSellerStoreService remoteSellerStoreService;
    @Resource
    ErpSellerStorePromotionActivityMapper erpSellerStorePromotionActivityMapper;
    @Resource
    RestTemplate restTemplate;
//    @Resource
//    PythonConfig pythonConfig;

    static String path = "http://47.94.131.193:8000";


//    @Override
//    public R<Object> setCommission(Long storeId, Long aeProductId, Integer commission) {
        //TODO 内部接口
//        ErpSellerStoreCookie sellerStoreCookie = erpSellerStoreCookieMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerStoreCookie>().eq(ErpSellerStoreCookie::getStoreId, storeId)
//        );
//
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("commission", commission.toString());
//        map.put("productId", aeProductId.toString());
//        map.put("cookie_str", sellerStoreCookie.getCookie());
//        System.out.println(map);
//        try {
//            ResponseEntity<String> forEntity = restTemplate
//                    .postForEntity(pythonConfig.getEndpoint() + "/affiliate/setCommission", map, String.class);
//            String body = (String) forEntity.getBody();
//            JSONObject bodyJson = JSONObject.parseObject(body);
//            Integer code = bodyJson.getInteger("code");
//            if (code == 200) {
//                return R.ok("设置成功");
//            } else {
//                return checkMsg(storeId, code, bodyJson.getString("msg"));
//            }
//        } catch (Exception e) {
//
//            return R.fail("联盟折扣设置异常|"+e.getMessage());
//        }
//    }

    @Override
    public R<Object> createActivityByPython(String storeId,
                                            String startTime,
                                            String endTime,
                                            String activityName) {
//        ErpSellerStorePromotionActivity activity = erpSellerStorePromotionActivityMapper.selectById(activityId);
//        if (ObjectUtils.isNull(activity)){
//            return R.fail("活动不存在");
//        }

        //获取店铺
        String cookie = queryCookieByStoreId(Long.valueOf(storeId));
        if (ObjectUtils.isNull(cookie)){
            return R.fail("获取cookie失败");
        }
        JSONObject object = new JSONObject();
        object.put("cookie_str",cookie);
        //开始时间转时间戳
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化当前时间


        LocalDateTime startTimeDT = LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime endTimeDT = LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        // 将 LocalDateTime 对象转换为 Instant 对象，该对象表示一个确切的时间点
//        Instant endTimeIT = endTimeDT.atZone(ZoneId.systemDefault()).toInstant();
//        Instant startTimeIT = startTimeDT.atZone(ZoneId.systemDefault()).toInstant();
//        long endTimestamp = endTimeIT.toEpochMilli();
//        long startTimestamp = startTimeIT.toEpochMilli();
        Long endTimestamp = endTimeDT.toEpochSecond(ZoneOffset.UTC);
        Long startTimestamp = startTimeDT.toEpochSecond(ZoneOffset.UTC);

        String endStr = endTimestamp.toString() + "000";
        String startStr = startTimestamp.toString() + "000";

        object.put("activityName",activityName);
        object.put("activityStartTime",startStr);
        object.put("activityEndTime",endStr);
        ResponseEntity<String> forEntity = restTemplate
                .postForEntity(path + "/activity/create", object, String.class);
        String body = (String) forEntity.getBody();
        System.out.println(body);
        JSONObject bodyJson = JSONObject.parseObject(body);
        Integer code = bodyJson.getInteger("code");
        if (code != 200) {
            return R.ok("失败");
        }
           return R.ok("设置成功");
    }

    @Override
    public R<Object> addProductToActivity(String storeId, String discount, String promotionId, String productId) {

        //获取店铺
        String cookie = queryCookieByStoreId(Long.valueOf(storeId));
        if (ObjectUtils.isNull(cookie)){
            return R.fail("获取cookie失败");
        }
        JSONObject object = new JSONObject();
        object.put("cookie_str",cookie);

        object.put("promotionId",promotionId);
        object.put("productId",productId);
        object.put("discount",discount);
        object.put("endTime","123");
        object.put("startTime","123");
        ResponseEntity<String> forEntity = restTemplate
                .postForEntity(path + "/activity/addProduct", object, String.class);
        String body = (String) forEntity.getBody();
        System.out.println(body);
        JSONObject bodyJson = JSONObject.parseObject(body);
        Integer code = bodyJson.getInteger("code");
        if (code != 200) {
            return R.fail(bodyJson.getString("msg"));
        }else {
            if (body.contains("SUCCESS::调用成功")){
                return R.ok("设置成功");
            }else {
                 return R.fail(bodyJson.getString("msg"));
            }
        }
    }

    /**
     * 检测侵权词
     * @param newSubject
     * @return
     */
    @Override
    public R<Object> checkViolationWords(String newSubject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("content",newSubject);

        ResponseEntity<String> forEntity = restTemplate
                .postForEntity(path + "/checkViolationWords", jsonObject, String.class);
        String body = (String) forEntity.getBody();
        System.out.println(body);
        JSONObject bodyJson = JSONObject.parseObject(body);
        if (ObjectUtils.isNull(bodyJson.getString("data"))){
            //无侵权词
            return R.ok("无侵权词");
        }else {
            //有侵权词
            String data = bodyJson.getString("data");
            return R.fail(data);
        }
    }

//    public R<Object> checkMsg(Long storeId, Integer code, String msg) {
//        if (code == 501 && msg.equals("用户cookie过期")) {
//            //将店铺cookie设置为失效
//            String cookie = remoteSellerStoreService.getCookieByStoreId(storeId);
//
//            if (ObjectUtils.isNotNull(cookie)){
//                //cookie不为空
//                cookie.setCookieStatus("0");
//                erpSellerStoreCookieMapper.updateById(cookie);
//            }
//            return R.fail(msg);
//        } else {
//            return R.fail();
//        }
//    }

    @Override
    public String queryCookieByStoreId(Long storeId) {
        Object cacheObject = RedisUtils.getCacheObject("store_cookie_key:" + storeId);
        String cookie = null;
        if (ObjectUtils.isNull(cacheObject)){
            cookie = remoteSellerStoreService.getCookieByStoreId(storeId);
            RedisUtils.setCacheObject("store_cookie_key:" + storeId, cookie);
        }else {
            cookie = cacheObject.toString();
        }
        return cookie;
    }


}
